package com.gcloud.mesh.dcs.chain.k8s;

import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.dcs.chain.FilterChain;
import com.gcloud.mesh.dcs.chain.IMigrationStepChain;
import com.gcloud.mesh.framework.core.SpringUtil;
import com.gcloud.mesh.sdk.GceSDK;
import com.gcloud.mesh.sdk.RestveleroSDK;
import com.gcloud.mesh.supplier.enums.SystemType;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.MyBusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class DeleteNamespace implements IMigrationStepChain {

    @Autowired
    private RestveleroSDK restveleroSDK;

    public void deleteSrcNameSpace(String nameSpaceId){
        try {
            GceSDK gceSDK = SpringUtil.getBean(GceSDK.class);
            //删除命名空间
            gceSDK.delateNamespace(nameSpaceId);
        } catch (Exception e) {
            log.error("删除源命名空间失败",e);
            throw new MyBusinessException("删除源命名空间失败::"+e.getMessage());
        }
    }

    @Override
    public void doExec(String schedulerJobId, String attach, FilterChain filterChain, IMigrationStepChain stepChain) {
        JSONObject jsonObject = JSONObject.parseObject(attach);
        String instanceId = jsonObject.getString("instanceId");
        this.deleteSrcNameSpace(instanceId);
        try{
            String srcUrl = jsonObject.getString("srcUrl");
            String dstUrl = jsonObject.getString("dstUrl");
            String backupName = jsonObject.getString("backupName");
            //删除velero中的备份数据和restore数据
            restveleroSDK.backupDelete(srcUrl,backupName);
            restveleroSDK.restoreDelete(dstUrl,backupName);
        }catch (Exception e){
            log.error("DeleteNamespace",e);
        }

        filterChain.doExec(schedulerJobId,attach,filterChain,stepChain);
    }

    @Override
    public String chainType() {
        return SystemType.K8S.getName();
    }

    @Override
    public String chainName(String attach) {
        JSONObject jsonObject = JSONObject.parseObject(attach);
        return String.format("%s删除命名空间",jsonObject.getString("srcDatacenterName"));
    }

    @Override
    public int getOrder() {
        return 3;
    }
}
